package com.ts.graphql.client;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.util.MultiValueMapAdapter;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 *
 * 发送 GraphQL 请求的工具类
 *
 * @author suyi
 */
public final class GraphQlUtil {

    private GraphQlUtil() {}

    private final static String QUERY_ARG_NAME = "query";
    /**
     *
     * 发送 GraphQL 请求
     *
     * @param url       GraphQL 请求端点
     * @param request   GraphQL 请求
     * @param headers   http 请求头
     * @return          请求响应结果
     */
    public static JSONObject send(String url, GraphQlRequest request, Map<String, String> headers) {
        return send(url, QUERY_ARG_NAME, request, headers);
    }

    private static JSONObject send(String url, String queryArgName, GraphQlRequest request, Map<String, String> headers) {
        RestTemplate template = new RestTemplate();

        HttpHeaders httpHeaders = new HttpHeaders();
        for (Map.Entry<String, String> entry : headers.entrySet()) {
            httpHeaders.add(entry.getKey(), entry.getValue());
        }

        HashMap<String, String> requestBodyMap = new HashMap<>(1);
        requestBodyMap.put(queryArgName, request.toString());
        String requestBody = JSON.toJSONString(requestBodyMap);
        HttpEntity<String> entity = new HttpEntity<>(requestBody, new MultiValueMapAdapter<>(httpHeaders));

        ResponseEntity<String> responseEntity = template.postForEntity(url, entity, String.class);

        return JSON.parseObject(responseEntity.getBody());
    }

}
